import { Menu } from 'antd'
import { Link, withRouter } from 'react-router-dom'
import { Fragment } from 'react'
import router from '@/router'
import { getParentPaths } from '@/utils/tools'
import settings from '@/settings'
import './sidebar.less'

const { SubMenu } = Menu
// const { Sider } = Layout

// 没有children的菜单
const renderMenu = ({ title, key, icon }) => {
  return (
    <Menu.Item key={key} icon={icon && icon()}>
      <Link to={key}>{title}</Link>
    </Menu.Item>
  )
}

// 有children的菜单
const renderSubMenu = ({ title, key, children, icon }) => {
  return (
    <SubMenu key={key} icon={icon && icon()} title={title}>
      {
        children && children.map(item => {
          return item.children && item.children.length > 0
            ? renderSubMenu(item)
            : renderMenu(item)
        })
      }
    </SubMenu>
  )
}

// 左侧导航栏
const Sidebar = (props) => {
  const selectedKeys = [props.location.pathname]
  const defaultSelectedKeys = [props.location.pathname]
  const defaultOpenKeys = getParentPaths(props.location.pathname)


  return (
    <Fragment>
      <div className="sidebar" style={{ width: !props.isCollapse && `${settings.sideWidth}px` || '0' }}>
        <Menu theme="light" style={{ borderRight: 0 }} mode="inline"
          selectedKeys={selectedKeys}
          defaultSelectedKeys={defaultSelectedKeys}
          defaultOpenKeys={defaultOpenKeys}
          inlineCollapsed={props.isCollapse}>
          {
            router && router.map(item => {
              return item.children && item.children.length > 0
                ? renderSubMenu(item)
                : renderMenu(item)
            })
          }
        </Menu>
      </div>
    </Fragment>
  )
}

export default withRouter(Sidebar)